//
//  QCSearchController.swift
//  爱汽车
//
//  Created by liujianlong on 2023/8/25.
//

import UIKit
import TCCKit
class QCSearchController: QCViewController {
    var index = 10000
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        QCTool.requestAboard({[weak self] in
            self?.initData()
        })
        initData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        BLE.stopScan()
        CCHud.stop()
    }
    override func initUI() {
        title = LS("蓝牙")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.setupRefreshing()
        tableView.updateBlock = {[weak self] in
            self?.initData()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) {[weak self] in
                self?.tableView.endRefreshing()
            }
        }
        tableView.register(QCSearchCell.self, forCellReuseIdentifier: QCSearchCell.ID())
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    override func initData(){
        
        index = 10000
        let filterProductName = productName()
//        APP.log.input.text = APP.log.input.text + "\n" + "productName = \(filterProductName)"
        
        BLE.scanWithOther = { peripheral in
            let product = String(format: "%.2X%.2X", peripheral.advertData[1],peripheral.advertData[0])
            return filterProductName.contains(product) || OTAName.contains(peripheral.name ?? "")
        }
        //"02E9D"
        BLE.scanWithServices = [TouchPad_service, Watch_service,Nordic_OTA_service]
        
        KBDevice.bg_findAllAsync(nil){[weak self] result in
            let array_result = result as? [KBDevice]
            BLE.startScan { array in
                for per in array{
                    if per.mac.count >= 0{
                        let device = KBDevice()
                        device.mac = per.mac
                        device.uuid = per.identifier.uuidString
                        device.bg_saveOrUpdateAsync()
                    }else{
                        let temp = array_result?.filter{($0 ).uuid == per.identifier.uuidString}
                        let device = temp?.last
                        per.mac = (device!).mac
                    }
                }
                DispatchQueue.main.async {
                    for i in 0..<BLE.searchedPeripherals.count{
                        let per  = BLE.searchedPeripherals[i]
                        if per.state == .connected{
                            self?.index = i
                        }
                    }
                    self?.tableView.reloadData()
                }
            }
        }
    }
    
    override var connectStatus: BLEStatus{
        didSet{
            index = 10000
            guard BLE.connectedPeripherals.count > 0 , let per = BLE.connectedPeripherals.first else{
                tableView.reloadData()
                return
            }
            for i in 0..<BLE.searchedPeripherals.count{
                if per == BLE.searchedPeripherals[i]{
                    index = i
                }
            }
            tableView.reloadData()
        }
    }
}
//MARK: - UITableViewDataSource
extension QCSearchController:UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return BLE.searchedPeripherals.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: QCSearchCell.ID()) as! QCSearchCell
        cell.name.text = BLE.searchedPeripherals[indexPath.row].name
        cell.mac.text = BLE.searchedPeripherals[indexPath.row].mac
        cell.img.image = UIImage(named:indexPath.row == index ? "选择" : "未选择")
        return cell
    }
}
//MARK: - UITableViewDelegate
extension QCSearchController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let current_p = BLE.searchedPeripherals[indexPath.row]
        guard BLE.connectedPeripherals.count > 0 , let p = BLE.connectedPeripherals.first, p.mac == current_p.mac else{
            index = indexPath.row
            tableView.reloadData()
            BLE.connect(current_p)
            CCHud.start()
            return
        }
        if p.mac == current_p.mac{
            alert(LS("提示"),LS("是否断开连接？"),nil, {
                BLE.disConnect(current_p)
            })
            //CCHud.start("该设备已连接", stopTime: 1.5)
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
